package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
测试synchronized和ReentrantLock是可重入锁。
可重入锁：同一个线程外层函数获取锁之后，内层函数仍然能获取该锁的代码，即在同一个线程在
    外层获取锁的时候，在进入内存方法会自动获取锁。
    线程可以进入任何一个它已经拥有锁所有同步者的代码块
 */
public class ReenterLockDemo {

    public static void main(String[] args) {

        Phone phone = new Phone();

            new Thread(() -> {
                    //线程要执行的代码
                try {
                    //线程在进入sendMS()时候，会自动回去sendEmail()方法的锁
                    phone.sendMS();//11	 invoked sendMS()   11	---- invoked sendEmail()

                } catch (Exception e) {
                    e.printStackTrace();
                }
            },"AAAA").start();

        new Thread(() -> {
            //线程要执行的代码
            try {
                phone.sendMS();//12	 invoked sendMS() 12	---- invoked sendEmail()

            } catch (Exception e) {
                e.printStackTrace();
            }
        },"BBB").start();

        System.out.println("------------");
        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(phone,"t3").start();
        new Thread(phone,"t4").start();
    }

}

class Phone implements Runnable {

    public synchronized void sendMS() throws Exception {
        //Thread.currentThread().getId()获取线程ID
        System.out.println(Thread.currentThread().getId() + "\t invoked sendMS()");

        sendEmail();

    }
    public synchronized void sendEmail() throws Exception {

        System.out.println(Thread.currentThread().getId() + "\t---- invoked sendEmail()");
    }

    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        get();
    }

    public void get() {

        lock.lock();
       // lock.lock();

        try {

            System.out.println(Thread.currentThread().getName() + "\t invoked get()");
            set();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //lock.unlock();
            lock.unlock();
        }
    }

    public void set() {

        lock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + "\t invoked set()");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}